package com.jzo2o.health.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.expcetions.DBException;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.health.enums.OrderPayStatusEnum;
import com.jzo2o.health.enums.OrderStatusEnum;
import com.jzo2o.health.mapper.OrdersCancelledMapper;
import com.jzo2o.health.mapper.OrdersMapper;
import com.jzo2o.health.model.UserThreadLocal;
import com.jzo2o.health.model.domain.Orders;
import com.jzo2o.health.model.domain.OrdersCancelled;
import com.jzo2o.health.model.dto.request.OrdersCancelReqDTO;
import com.jzo2o.health.service.IOrdersCancelledService;
import com.jzo2o.health.service.IOrdersRefundService;
import com.jzo2o.health.service.IOrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 订单取消表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-12-15
 */
@Slf4j
@Service
@Transactional
public class OrdersCancelledServiceImpl extends ServiceImpl<OrdersCancelledMapper, OrdersCancelled> implements IOrdersCancelledService {

    private List<Integer> cancelStatusList = Arrays.asList(OrderStatusEnum.NO_PAY.getStatus(), OrderStatusEnum.WAITING_CHECKUP.getStatus());
    @Resource
    private OrdersMapper ordersMapper;
    @Resource
    private IOrdersService ordersService;
    @Resource
    private IOrdersRefundService ordersRefundService;

    @Resource
    private IOrdersCancelledService ordersCancelledService;

    /**
     * 取消订单
     *
     * @param ordersCancelReqDTO
     */
    @Override
    public void cancel(OrdersCancelReqDTO ordersCancelReqDTO) {
        Long id = ordersCancelReqDTO.getId();
        Orders orders = ordersMapper.selectById(id);
        if (orders == null) {
            throw new BadRequestException("订单不存在");
        }
        //2.判断订单状态是否合法（必须是未支付或派单中）
        if (!cancelStatusList.contains(orders.getOrderStatus())){
            throw new BadRequestException("订单状态不合法");
        }
        //3. 如果是未支付 - 取消订单
        if (ObjectUtils.equals(orders.getOrderStatus(), OrderPayStatusEnum.NO_PAY.getStatus())){
            //1. 添加取消记录
            ordersCancelledService.addCancelRecord(ordersCancelReqDTO);
            //2. 更新订单状态 update orders set orders_status=600 where id=?
            boolean resultForOrders = ordersService.lambdaUpdate()
                    .eq(Orders::getId, id)
                    .set(Orders::getOrderStatus, OrderStatusEnum.CANCELLED.getStatus())
                    .update();
            if (!resultForOrders){
                throw new DBException("更新订单状态失败");
            }
        } else {
            //已支付订单取消
            ordersCancelledService.addCancelRecord(ordersCancelReqDTO);
            ordersRefundService.refund(orders);
        }


    }
    //创建订单取消表记录
    public void addCancelRecord(OrdersCancelReqDTO ordersCancelReqDTO){
        OrdersCancelled ordersCanceled = new OrdersCancelled();
        ordersCanceled.setId(ordersCancelReqDTO.getId());//设置订单id
        ordersCanceled.setCancellerId(UserThreadLocal.currentUserId());//取消人id
        ordersCanceled.setCancellerName(UserThreadLocal.currentUser().getName());//取消人名称
        ordersCanceled.setCancellerType(UserThreadLocal.currentUser().getUserType());//取消人类型
        ordersCanceled.setCancelReason( ordersCancelReqDTO.getCancelReason());//取消原因
        ordersCanceled.setCancelTime(LocalDateTime.now());//取消时间
        boolean resultForCancel = this.save(ordersCanceled);
        if (!resultForCancel){
            throw new DBException("添加取消记录失败");
        }
    }

}
